import React, { useState } from 'react';

const Index = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await fetch('/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    password
                })
            });
            const result = await response.json();
            if (response.ok) {
                window.location.href = '/login';
            } else {
                setError(result.error);
            }
        } catch (error) {
            setError('请求出错: ' + error.message);
        }
    };

    return (
        <div>
            <h1>注册</h1>
            <form onSubmit={handleSubmit}>
                <label>
                    用户名:
                    <input
                        type="text"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        required
                    />
                </label>
                <br />
                <label>
                    密码:
                    <input
                        type="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />
                </label>
                <br />
                <input type="submit" value="注册" />
            </form>
            {error && <p style={{ color: 'red' }}>{error}</p>}
        </div>
    );
};

export default Index;
